#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <iostream>
#include <time.h>

using namespace std;

int getlen(unsigned char* str,int arraylen)
{
    int num = 0;
    for(int i = 0; i < arraylen; i++)
    {
        if(int(str[i]) == 0) return num;
        num++;
    }
    return num;
}

int main()
{
    char* portname = "/dev/ttyUSB2"; // 默认选择ttyUSB1设备，则默认程序控制ttyUSB1
    struct termios Opt;
    int fd;
    int rdlen;
    int status;
    int readflag = 1;
    unsigned char buf[800];
    clock_t start,end;
    // open返回句柄，其实就是一个用来代表状态的数字，愣要说这么🐮
    fd = open(portname, O_RDWR|O_NOCTTY|O_DSYNC);
    std::cout<<"输入数字1、2选择读写状态，1代表读入，2代表写"<<std::endl;
    std::cin>>status;
    cout<<endl;
    cout<<"进入交互模式"<<endl;
    cout<<"==========="<<endl;
    start = clock();
    if(status == 1)
    {
        // 跳转到读入状态之后，等待10s如果未插入串口则退出程序
        if(fd < 0) 
        {
            cout<<"请插入并打开串口模块，或串口打开错误"<<endl;
        }
        start = clock();
        while(1)
        {
            fd = open(portname, O_RDWR|O_NOCTTY|O_DSYNC);
            if(fd > 0) break;
            if((end-start)/CLOCKS_PER_SEC > 10) {cout<<"10s内未插入串口读入失败"<<endl;return 0;}
        }
        cout<<"成功打开"<<endl;
        while(1)
        {

            memset(buf,0,sizeof(buf));
            rdlen = read(fd,buf,sizeof(buf)-1);
            if(rdlen > 0)
            {
                cout<<"读入数据:";
                cout<<buf<<endl;
                cout<<"==========="<<endl;
                readflag = 1;
                tcflush(fd, TCIOFLUSH);
            }
            else
            {
                if(readflag == 1)
                {
                    cout<<"readno"<<endl;
                    cout<<"==========="<<endl;
                    readflag = 0;
                }
            }
            
        }
    }
    if(status == 2)
    {
        if(fd < 0) 
        {
            cout<<"请插入并打开串口模块，或串口打开错误"<<endl;
        }
        start = clock();
        while(1)
        {
            fd = open(portname, O_RDWR|O_NOCTTY|O_DSYNC);
            if(fd > 0) break;
            if((end-start)/CLOCKS_PER_SEC > 10) {cout<<"10s内未插入串口读入失败"<<endl;return 0;}
        }
        cout<<"成功打开"<<endl;
        while(1)
        {
            memset(buf,0,sizeof(buf));
            cin>>buf;
            rdlen = write(fd,buf,getlen(buf,800));
        }
    }
    return 0;
}